package com.tom;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.tom.Contants.SESSION_TIMEOUT;

/**
 * 服务发现
 *
 * @author yanghongjun19
 * @date 2021/01/06
 **/
@Slf4j
public class RpcDiscover {

    private ZooKeeper zooKeeper;
    private List<String> serverList;

    /**
     * 需要传入zookeeper链接 比如: localhost:2181,localhost:2182,localhost:2183
     *
     * @param zookeeperCon
     */
    public RpcDiscover(String zookeeperCon) throws Exception {
        zooKeeper = new ZooKeeper(zookeeperCon, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if (watchedEvent.getType().equals(Event.EventType.NodeChildrenChanged)) {
                    log.info("节点发生变化");
                    watchNode();
                }
            }
        });
    }

    /**
     * 获取节点内容
     */
    private void watchNode() {
        try {
            //获取子节点信息
            List<String> nodeList = zooKeeper.getChildren(Contants.REGISTRY_PATH, true);
            List<String> dataList = new ArrayList<>();
            for (String node : nodeList) {
                byte[] bytes = zooKeeper.getData(Contants.REGISTRY_PATH + "/" + node, false, null);
                dataList.add(new String(bytes));
            }
            this.serverList = dataList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取可用的服务地址
     *
     * @return 服务地址
     */
    public String discover() {
        int size = serverList.size();
        if (size > 0) {
            int index = new Random().nextInt(size);
            return serverList.get(index);
        }
        throw new RuntimeException("没有找到对应的服务器");
    }
}
